$(function () {
    $("#jqGrid").jqGrid({
        url: '../sys/user/list',
        datatype: "json",
        colModel: [			
			{ label: '用户ID', name: 'userId', index: "user_id", width: 45, key: true ,hidden:true},
            { label: '手机号', name: 'mobile', width: 100 },
			{ label: '用户名', name: 'username', width: 75 },
            { label: '姓名', name: 'userdesc', width: 75 },
			{ label: '邮箱', name: 'email', width: 90 },
            { label: '公司', name: 'company', width: 100 },
            { label: '部门', name: 'dept', width: 100 },
            { label: '岗位', name: 'post', width: 100 ,formatter:getDictInfo },
            { label: '角色', name: 'roleName', width: 100 },
            { label: '内部数据权限', name: 'ifsuperdept', width: 150 ,formatter:getDictInfo},
            { label: '结算点级别', name: 'settlementinfo', width: 120  ,formatter:getDictInfo},
            { label: '外部数据权限', name: 'settlementleverName', width: 180 },
            { label: '外部数据权限', name: 'settlementlever', width: 100,hidden:true },


            { label: '是否主管', name: 'issupervisor', width: 80 ,
                formatter:function(v){
                    if(v=="0"){
                        return "是";
                    }else  if(v=="1"){
                        return "否"
                    }else {
                        return "";
                    }
                } },
			{ label: '状态', name: 'status', width: 80, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">禁用</span>' : 
					'<span class="label label-success">正常</span>';
			}},
			{ label: '创建时间', name: 'createTime', index: "create_time",  width: 86, formatter:"date", formatoptions: {newformat:'Y-m-d'}
            }
        ],
		viewrecords: true,
        height: 360,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        shrinkToFit:false,
        autoScroll: false,
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });

    var r = utils.getDictList("ifsuperdept,qxjb,station,setlever");
    vm.dictList1 = r.ifsuperdept;
    vm.dictList2 = r.qxjb;
    vm.dictList3 = r.station;
    vm.dictList4 = r.setlever;

});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			username: null
		},
		showList: true,
		title:null,
		roleList:{},
		user:{
			status:1,
			 roleIdList:[],
            name:""
		},
        dictList1:{},
        dictList2:{},
        dictList3:{},
        dictList4:{},
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.roleList = {};
			vm.user = {issupervisor:"1",status:1,roleIdList:[],dept:"",roleName:"",settlementlever:"",settlementleverName:""};
            $('#dept').attr("disabled", false);
            $('#post').attr("disabled", false);
			//获取角色信息
			this.getRoleList();
		},
		update: function () {
			var userId = getSelectedRow();
			if(userId == null){
				return ;
			}
            $('#dept').attr("disabled", true);
            $('#post').attr("disabled", true);
			vm.showList = false;
            vm.title = "修改";
			
			vm.getUser(userId);
			//获取角色信息
			this.getRoleList();
		},
		del: function () {
			var userIds = getSelectedRows();
			if(userIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../sys/user/delete",
                    contentType: "application/json",
				    data: JSON.stringify(userIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
                                vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function (event) {
			var url = vm.user.userId == null ? "../sys/user/save" : "../sys/user/update";
			$.ajax({
				type: "POST",
			    url: url,
                contentType: "application/json",
			    data: JSON.stringify(vm.user),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		getUser: function(userId){
			$.get("../sys/user/info/"+userId, function(r){
				vm.user = r.user;
			});
		},
		getRoleList: function(){
			$.get("../sys/role/select", function(r){
				vm.roleList = r.list;
			});
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
		},
        selectDept: function(){
            popPage.popOfficeGrid();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['370px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popOffice"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popOfficeGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var rowData=grid.jqGrid("getRowData",rowKey);
                  /*  if(rowData.isConmpany=='Y'){
                        alert("不能选择公司，请选择部门");
                        return ;
                    }*/
                    vm.user.dept = rowData.name;
                    vm.user.deptNo = rowData.id;
                    var id=rowData.parentId;
                    vm.user.companyid=id;

                    $.get("../sysoffice/info/"+id, function(r){
                        vm.user.company=r.sysOffice.name;;
                    });
                    layer.close(index);
                }
            });
        },

        selectRole: function(){
             popPage.popRoleGrid();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择角色",
                area: ['540px', '350px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popRole"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popRoleGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var ids= grid.getGridParam("selarrrow");

                    var len = ids.length;
                    var roleNames;
                    var roleIds;
                    vm.user.roleIdList=[];
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        vm.user.roleIdList.push(rowData.roleId);
                      if(i==0){
                          roleNames=rowData.roleName;
                          roleIds=rowData.roleId;

                      }else{
                          roleNames+=","+rowData.roleName;
                          roleIds+=","+rowData.roleId;
                      }

                    }
                    vm.user.roleName=roleNames;
                    vm.user.roleId=roleIds;

                  /*  var grid = $("#popRoleGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }
                    var rowData=grid.jqGrid("getRowData",rowKey);*/


                    layer.close(index);
                }
            });
        },

        selectunit: function () {
            var settlementinfo = vm.user.settlementinfo;
            console.log(settlementinfo);
            if (settlementinfo == "qxjb01") {//责任区域
                this.responseArea();
            } else if (settlementinfo == 'qxjb02' ) {//责任部门
                this.selectDept1();
            } else if (settlementinfo == 'qxjb03') {//责任人
                this.popUser();
            } else {
                alert("请选择结算点级别名称！");
                return;
            }
        },

        selectDept1: function(){
            popPage.popDeptGrid('','','Y');

            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['290px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#windowunit"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGridselect");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }
                    var ids= grid.getGridParam("selarrrow");
                    var len = ids.length;
                    var names;
                    var idss;
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        if(i==0){
                            names=rowData.name;
                            idss= rowData.id;
                        }else{
                            names+=","+rowData.name;
                            idss+=","+rowData.id;

                        }

                    }
                    vm.user.settlementleverName=names;
                    vm.user.settlementlever=idss;


                    layer.close(index);
                }
            });
        },

        popUser: function(){
            popPage.popUserGrid('','',true);
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择人",
                area: ['750px', '400px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#popUser"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#popUserGrid");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }
                    var ids= grid.getGridParam("selarrrow");
                    var len = ids.length;
                    var userIds;
                    var names;
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        if(i==0){
                            userIds=rowData.userId;
                            names=rowData.userdesc;
                        }else{
                            userIds+=","+rowData.userId;
                            names+=","+rowData.userdesc;
                        }

                    }
                    vm.user.settlementlever=userIds;
                    vm.user.settlementleverName=names;

                    layer.close(index);
                }
            });
        },


        responseArea: function(){
            $("#jqGridselect1").jqGrid({
                url: '../sysdict/list',
                datatype: "json",
                postData: {"type":"setlever"},
                colModel: [
                    { label: 'ID', name: 'id', index: "id", width: 45, key: true },
                    { label: '名称', name: 'label', index: "label", width: 200 },
                    { label: '值', name: 'value', index: "value",hidden:true},

                ],
                viewrecords: true,
                height: 200,
                rowNum: 1000,
                /*   rowList : [10,30,50],*/
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                // shrinkToFit:false,
                autoScroll: false,
                //pager: "#popOfficeGridPager",
                jsonReader : {
                    root: "page.list",
                   /* page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"*/
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridselect1").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });

      /*      $("#jqGridselect1").jqGrid("clearGridData");
             $("#jqGridselect1").jqGrid('getGridParam','page');
            $("#jqGridselect1").jqGrid('setGridParam',{
                url: '../sysdict/list',
                datatype: "json",
                postData: {"type":"setlever"},
            }).trigger("reloadGrid");
*/
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择区域",
                area: ['330px', '340px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#windowunit1"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGridselect1");
                    var rowKey = grid.getGridParam("selrow");
                    if(!rowKey){
                        alert("请选择一条记录");
                        return ;
                    }

                    var ids= grid.getGridParam("selarrrow");
                    var len = ids.length;
                    var values;
                    var names;
                    for(var i = 0;i < len ;i ++) {
                        var rowData=grid.jqGrid("getRowData",ids[i]);
                        if(i==0){
                            values=rowData.value;
                            names=rowData.label;
                        }else{
                            values+=","+rowData.value;
                            names+=","+rowData.label;

                        }

                    }
                    vm.user.settlementlever=values;
                    vm.user.settlementleverName=names;


                    layer.close(index);
                }
            });
        },

     /*   infoChange: function () {
            debugger;
             vm.user.settlementleverName="";
            vm.user.settlementlever="";
        },*/

	}
});

function infoChange(){
    vm.user.settlementleverName="";
    vm.user.settlementlever="";
}
